<template>
  <div>
      <!-- 面包屑导航 -->
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{path:'/home'}">首页</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户列表</el-breadcrumb-item>
      </el-breadcrumb>
      <!-- 卡片视图 -->
      <el-card>
        <!-- 搜索框 -->
        <el-row :gutter="20">
          <el-col :span="8">
          <el-input placeholder="请输入搜索内容" v-model="queryInfo.query" @clear="getUserList" clearable>
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
          </el-col>
          <el-col :span="4">
            <el-button type="primary" @click="addDialogVisible = true">添加用户</el-button>
          </el-col>
        </el-row>
        <!-- 用户列表 -->
        <el-table :data="users" border stripe>
          <el-table-column label="ID" type="index"></el-table-column>
          <el-table-column label="用户名" prop="username"></el-table-column>
          <el-table-column label="邮箱" prop="email"></el-table-column>
          <el-table-column label="手机" prop="mobile"></el-table-column>
          <el-table-column label="角色" prop="role_name"></el-table-column>
          <el-table-column label="状态">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button size="mini" type="success" icon="el-icon-edit" @click="showEditDialog(scope.row.id)"></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteUser(scope.row)"></el-button>
              <el-tooltip effect="dark" placement="top" content="权限" :enterable="false">
                <el-button size="mini" type="warning" icon="el-icon-s-tools" @click="showSetRoleDialog(scope.row)"></el-button>
              </el-tooltip>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页栏 -->
        <el-pagination         
          :current-page="queryInfo.pagenum"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :page-sizes="[1, 2, 5, 10]"
          :page-size="queryInfo.pagesize"
          layout="total, sizes, prev, pager, next, jumper"
          :total="totalpage">
        </el-pagination>
      </el-card>
      <!-- 添加用户对话框 -->
      <el-dialog title="添加用户" :visible.sync="addDialogVisible" width="50%" 
        :close-on-click-modal="false" @close="addDialogClose">
        <el-form ref="addFormRef" :model="addForm" :rules="addFormRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input v-model="addForm.username"></el-input>
          </el-form-item>
          <el-form-item label="密码" prop="password">
            <el-input v-model="addForm.password" showPassword></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="addForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="addForm.mobile"></el-input>
          </el-form-item>         
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="addDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 修改用户对话框 -->
      <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" 
        :close-on-click-modal="false" >
        <el-form ref="editFormRef" :model="editForm" :rules="addFormRules" label-width="70px">
          <el-form-item label="用户名" prop="username">
            <el-input :value="editForm.username" disabled></el-input>
          </el-form-item>
          <el-form-item label="邮箱" prop="email">
            <el-input v-model="editForm.email"></el-input>
          </el-form-item>
          <el-form-item label="手机号" prop="mobile">
            <el-input v-model="editForm.mobile"></el-input>
          </el-form-item>         
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="editDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editUser">确 定</el-button>
        </div>
      </el-dialog>
      <!-- 分配角色对话框 -->
      <el-dialog title="分配用户" :visible.sync="roleDialogVisible" width="50%" 
        :close-on-click-modal="false" >
        <div>
          <p>当前用户：{{curUser.username}}</p>
          <p>当前角色：{{curUser.role_name}}</p>
          <el-select v-model="curRoleId" placeholder="请选择">
            <el-option
              v-for="role in roleList"
              :key="role.id"
              :label="role.roleName"
              :value="role.id">
            </el-option>
          </el-select>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="roleDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="setUserRole">确 定</el-button>
        </div>
      </el-dialog>
  </div>
  
</template>

<script>
export default {
  data() {
    var checkPassword = (rule, value, callback) => {
      var lvl=0;
      if(/[0-9]/.test(value)&&/[a-z]/.test(value)&&/[A-Z]/.test(value))
        callback();
      else 
        callback('必须同时包含大小写字母和数字');
    };
    return {
      queryInfo: {
        query: '',
        pagenum: 1,
        pagesize: 5
      },
      totalpage: 0,
      users: [],
      roleList: [],
      addDialogVisible: false,
      editDialogVisible: false,
      roleDialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      editForm: {
        id: '',
        username: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max:10, message: '长度在3-10个字符之间', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 3, max:16, message: '长度在3-16个字符之间', trigger: 'blur' },
          { validator: checkPassword, trigger: 'blur' }
        ]
        ,
        email: [
          { required: true, type: 'email', message: '请输入正确的邮箱', trigger: 'blur' }
        ],
        mobile: [
          { required: true, trigger: 'blur', message: '请输入正确的手机号',
            pattern:/^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/ }
        ]
      },
      curUser: {},
      curRoleId: null
    }
  },
  created() {
    this.getUserList();
  },
  methods: {
    async getUserList() {
      const { data: res } = await this.$http.get('users', { params: this.queryInfo });
      console.log('users', res);
      if (res.meta.status == 200) {
        this.users = res.data.users;
        this.totalpage = res.data.total;
        this.queryInfo.pagenum = res.data.pagenum;
      } else {
        this.$message.error(res.meta.msg);
      }
    },
    handleSizeChange(size) {
      this.queryInfo.pagesize=size;
      this.getUserList();
    },
    handleCurrentChange(page) {
      this.queryInfo.pagenum=page;
      this.getUserList();
    },
    async userStateChange(user) {
      console.log(user);
      const { data: res } = await this.$http.put(`users/${user.id}/state/${user.mg_state}`);
      if(res.meta.status == 200) {
        this.$message.success('更新用户状态成功!');
      } else {
        user.mg_state=!user.mg_state;
        this.$message.error('更新用户状态失败!');
      }
    },
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    addUser() {
      this.$refs.addFormRef.validate(async (valid)=>{
        if(!valid) return;
        const { data: res } = await this.$http.post('users', this.addForm);
        if( res.meta.status == 201 )
        {
          this.addDialogVisible=false;
          this.$message.success('添加成功！');
          this.getUserList();
        }
        else
        {
          this.$message.error('添加失败！');
        }
      });      
    },
    async showEditDialog(id) {
      const { data: res } = await this.$http.get(`users/${id}`);
      if( res.meta.status == 200 )
        {
          console.log(res);
          this.editForm.id=id;
          this.editForm.username=res.data.username;
          this.editForm.email=res.data.email;
          this.editForm.mobile=res.data.mobile;
          this.editDialogVisible=true;
        }
        else
        {
          this.$message.error('查询用户信息失败！');
        }
    },
    editUser() {
      this.$refs.editFormRef.validate(async (valid)=>{
        if(!valid) return;
        const { data: res } = await this.$http.put(`users/${this.editForm.id}`,this.editForm);
        if( res.meta.status == 200 )
        {
          this.editDialogVisible=false;
          this.$message.success('修改成功！');
          this.getUserList();
        }
        else
        {
          this.$message.error('修改失败！');
        }
      });      
    },
    async deleteUser(user) {
      const result = await this.$confirm(`确定要删除用户：${user.username}？`,'确认',{
        type: 'warning'
      }).catch(err=>err);
      if(result=='confirm') {
        console.log('删除')
        const { data: res } = await this.$http.delete(`users/${user.id}`);
        if( res.meta.status == 200 )
        {
          this.$message.success('删除成功！');
          this.getUserList();
        }
        else
        {
          this.$message.error('删除失败！');
        }
      }
    },
    async showSetRoleDialog(user) {
      this.curUser=user;
      this.curRoleId=null;
      //获取所有角色
      const {data:res} = await this.$http.get('roles');
      if(res.meta.status!=200) {
        return this.$message.error('获取角色列表失败');
      }
      this.roleList=res.data;
      this.roleDialogVisible=true;
    },
    async setUserRole() {
      const {data:res} = await this.$http.put(`users/${this.curUser.id}/role`,{rid:this.curRoleId||0});
      if(res.meta.status!=200) {
        return this.$message.error('分配用户角色失败！'+res.meta.msg);
      }
      this.getUserList();
      this.$message.success('分配用户角色成功！');
      this.roleDialogVisible=false;
    }
  }

}
</script>

<style lang="less" scoped>

</style>